package com.example.aipdefficiency.service;

import com.example.aipdefficiency.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VerifyCodeService {
    
    @Autowired
    private RedisUtil redisUtil;
    
    private static final String VERIFY_CODE_PREFIX = "verify_code:";
    private static final int VERIFY_CODE_LENGTH = 6;
    private static final int VERIFY_CODE_EXPIRE_MINUTES = 5;
    
    /**
     * 生成并发送验证码
     * @param mobile 手机号
     * @return 验证码
     */
    public String generateAndSendVerifyCode(String mobile) {
        // 生成6位数字验证码
        String verifyCode = generateVerifyCode();
        
        // 存储到Redis，5分钟过期
        String key = VERIFY_CODE_PREFIX + mobile;
        redisUtil.set(key, verifyCode, VERIFY_CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);
        
        // 这里应该调用短信服务发送验证码
        // 为了演示，我们只是打印日志
        log.info("发送验证码到手机号 {}: {}", mobile, verifyCode);
        
        return verifyCode;
    }
    
    /**
     * 验证验证码
     * @param mobile 手机号
     * @param code 验证码
     * @return 是否验证成功
     */
    public boolean verifyCode(String mobile, String code) {
        String key = VERIFY_CODE_PREFIX + mobile;
        Object storedCode = redisUtil.get(key);
        
        if (storedCode == null) {
            log.warn("验证码已过期，手机号: {}", mobile);
            return false;
        }
        
        boolean isValid = storedCode.toString().equals(code);
        if (isValid) {
            // 验证成功后删除验证码
            redisUtil.delete(key);
            log.info("验证码验证成功，手机号: {}", mobile);
        } else {
            log.warn("验证码验证失败，手机号: {}, 输入验证码: {}", mobile, code);
        }
        
        return isValid;
    }
    
    /**
     * 生成随机验证码
     * @return 验证码
     */
    private String generateVerifyCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < VERIFY_CODE_LENGTH; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
} 